package org.daochong.web.filter;

import java.io.IOException;
import java.util.Collection;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookiesFilter implements Filter {
	public void destroy() {
	}

	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) resp;
		filterChain.doFilter(req, resp);
		Collection<String> cookies = response.getHeaders("Set-Cookie");
		boolean first = true;
		boolean https = request.getScheme().equalsIgnoreCase("https");
		for (String str : cookies) {
			if (str.indexOf(" HttpOnly") == -1) {
				str = str + (str.endsWith(";") ? "" : ";") + " HttpOnly";
			}
			if ((https) && (str.indexOf(" Secure") == -1)) {
				str = str + (str.endsWith(";") ? "" : ";") + " Secure";
			}
			if (first) {
				first = false;
				response.setHeader("Set-Cookie", str);
			} else {
				response.addHeader("Set-Cookie", str);
			}
		}
	}

	public void init(FilterConfig config) throws ServletException {
	}
}